package com.wjc.basemodule.base

import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.ViewStub
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.util.forEach
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.fangpao.common.permission.AbsPermissionCallbacks
import com.fangpao.common.permission.PermissionCallbacks
import com.wjc.basemodule.BR
import com.wjc.basemodule.R
import com.wjc.basemodule.permission.EasyPermissions
import com.wjc.basemodule.widget.DialogManager
import java.lang.reflect.Field


/**
 * ClassName: com.wjc.basemodule.base
 * Description:
 * JcChen on 2020.09.21.7:52 PM
 */
abstract class BaseActivity<DB : ViewDataBinding> : AppCompatActivity(), PermissionCallbacks {
    private val TAG = "BaseActivityKt"

    private var defaultPage: DefaultPage? = null
    private var mActivityProvider: ViewModelProvider? = null
    private var mDialogManager: DialogManager? = null

    //    private var noContentView: View? = null
//    private var networkErrorOrNoDataView: View? = null
//    private var progressBar: ProgressBar? = null
    protected abstract val dataBindingConfig: DataBindingConfig

    protected lateinit var binding: DB


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewModel()
        binding = DataBindingUtil.setContentView(this, dataBindingConfig.layout)
        binding.lifecycleOwner = this

        if (dataBindingConfig.stateViewModel != null) {
            binding.setVariable(BR.vm, dataBindingConfig.stateViewModel)
        }
        dataBindingConfig.bindingParams.forEach { index, param -> binding.setVariable(index, param) }

        val loadingView = binding.root.findViewById<View>(R.id.loading_progress)
        val defaultView = binding.root.findViewById<View>(R.id.vs_error_or_no_data_container)

        defaultPage = DefaultPage(loadingView, if (defaultView is ViewStub) defaultView else null)
    }


    /**
     * 初始化viewModel
     * 之所以没有设计为抽象，是因为部分简单activity可能不需要viewModel
     * observe同理
     */
    open fun initViewModel() {
    }


    override fun onDestroy() {
        super.onDestroy()
        if (mDialogManager != null) {
            mDialogManager!!.dismissDialog()
            mDialogManager = null
        }
    }


    val dialogManager: DialogManager
        get() = mDialogManager ?: DialogManager(this)


    /**
     * 权限回调接口  start
     */
    var permissListener: AbsPermissionCallbacks? = null

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsAllGranted() {
        permissListener?.onPermissionsAllGranted()
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        permissListener?.onPermissionsDenied(requestCode, perms)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        permissListener?.onPermissionsGranted(requestCode, perms)
    }

    override fun onPermissionsHasGranted(requestCode: Int) {
        permissListener?.onPermissionsHasGranted(requestCode)
    }


    fun checkCusPermission(
        listener: AbsPermissionCallbacks,
        resString: Int,
        vararg mPerms: String?
    ) {
        if (EasyPermissions.hasPermissions(this, *mPerms)) {
            listener.onPermissionsHasGranted(200)
        } else {
            permissListener = listener
            EasyPermissions.requestPermissions(this, getString(resString), 200, *mPerms)
        }
    }

    /**
     * 权限回调接口  end
     */

    protected fun <T : ViewModel?> getActivityViewModel(modelClass: Class<T>): T {
        if (mActivityProvider == null) {
            mActivityProvider = ViewModelProvider(this)
        }
        return mActivityProvider!![modelClass]
    }

    //    companion object {

    //    protected const val RC_PERM = 123
    private fun fixInputMethodManagerLeak(destContext: Context?) {
        if (destContext == null) {
            return
        }
        val imm = destContext.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        val arr = arrayOf("mCurRootView", "mServedView", "mNextServedView")
        var f: Field? = null
        var objGet: Any? = null
        for (i in arr.indices) {
            val param = arr[i]
            try {
                f = imm.javaClass.getDeclaredField(param)
                if (!f.isAccessible) {
                    f.isAccessible = true
                }
                objGet = f[imm]
                if (objGet != null && objGet is View) {
                    if (objGet.context === destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f[imm] = null // 置空，破坏掉path to gc节点
                    } else {
                        // 不是想要目标销毁的，即为又进了另一层界面了，不要处理，避免影响原逻辑,也就不用继续for循环了
                        break
                    }
                }
            } catch (t: Throwable) {
                t.printStackTrace()
            }
        }
    }
//    }
}